//
//  QDStationResultTableViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/2/27.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit

private extension String {
    
    /// 搜索结果的字符串
    func searchResultString(key: String) -> NSAttributedString {
        
        guard !self.isEmpty, self.contains(key) else { return NSAttributedString(string: "") }
        
        let nsSelf = self as NSString
        
        //默认全部变为默认字符串
        let attribute = NSMutableAttributedString(string: self, attributes: [.foregroundColor : QDColors.black,
                                                                             .font: Font.regular.font(size: 16)])
        //转成NSString
        let range = nsSelf.range(of: key)
        
        //根据range设置高亮状态
        attribute.addAttribute(.foregroundColor, value: QDColors.theme, range: range)
        
        return attribute
    }
}

/// 站点搜索结果展示的cell
private final class QDStationResultTableViewCell: NWTableViewCell {
    
    /// 展示站点名称的标签
    let titleLabel = UILabel()
    
    override func buildView() {
        super.buildView()
        
        bottomLineInset.left = 20
        bottomLineInset.right = 20
        bottomLineView.backgroundColor = #colorLiteral(red: 0.9294117647, green: 0.9411764706, blue: 0.9333333333, alpha: 1)
        bottomLineHeight = 0.5
        
        contentView.addSubview(titleLabel)
        
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.height.equalTo(22)
            make.top.equalToSuperview().offset(16)
        }
    }
}


protocol QDStationResultTableViewAction: QDStationsViewSelectAction {
    
    func stationResultTableViewController(viewController: QDStationResultTableViewController,textFieldShouldFill stationName: String, stationId: String, line: [String])
}


extension QDStationResultTableViewAction {
    
    func stationResultTableViewController(viewController: QDStationResultTableViewController,textFieldShouldFill stationName: String, stationId: String, line: [String]){}
}


/// 站点搜索结果的控制器
final class QDStationResultTableViewController: NWTableViewController {

    /// 所有的站点
    var allStations = [QDMetroStation]()
    ///选中响应
    weak var selectAction: QDStationResultTableViewAction?
    
    /// 放置结果
    var result:[QDMetroStation] = [] {
        willSet {
            // 结果列表
            tableView.isHidden = newValue.count == 0
        }
        didSet {
            if result.count > 0 {//如果搜索有结果
                tableView.reloadData()
            }
        }
    }
    
    /// 放置搜不到图标的视图
    private let iconImageView = UIImageView()
    /// 放置搜不到的语言描述
    private let iconLabel = UILabel()
    /// 搜索的key
    private var searchKey = ""
    

    override func loadPropertysAtInitialization() {
        super.loadPropertysAtInitialization()
        
        headerRefreshEnable = false
        footerRefreshEnable = false
        tableView.rowHeight = 54
    }
    
    
    override func registerTableViewCellsAndReusableView() {
        tableView.register(QDStationResultTableViewCell.self, forCellReuseIdentifier: "cell")
    }
    
    
    /// 开始搜索
    func search(key: String){
    
        searchKey = key
        result = allStations.filter { $0.name.contains(key) }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        iconImageView.clipsToBounds = true
        iconImageView.contentMode = .scaleAspectFill
        iconImageView.image = "sta_none".namedImage
        
        iconLabel.textColor = QDColors.gray2
        iconLabel.font = Font.regular.font(size: 15)
        iconLabel.text = "没有找到你搜索的站点呢~"
        
        view.addSubview(iconImageView)
        view.addSubview(iconLabel)
        
        iconImageView.snp.makeConstraints { (make) in
            make.width.height.equalTo(160)
            make.centerX.equalToSuperview()
            make.bottom.equalTo(iconLabel.snp.top).inset(4)
        }
        
        iconLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview().offset(3.5)
            make.centerX.equalToSuperview()
            make.height.equalTo(22)
        }
        
        view.bringSubviewToFront(tableView)
        tableView.isHidden = true
    }
}


extension QDStationResultTableViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return result.count
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        
        if let resultCell = cell as? QDStationResultTableViewCell {
            //进行赋值
            let station = result[indexPath.row]
            resultCell.titleLabel.attributedText = station.name.searchResultString(key: searchKey)
            resultCell.bottomLineView.isHidden = indexPath.row == result.count
        }
        
        return cell
    }
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let station = result[indexPath.row]
        
        //如果搜索出的站点不能使用，弹出
        if station.disable {
            view.showTextHUD(text: "暂未开通"); return
        }
        
        selectAction?.stationsViewController(didSelect: station.name, stationId: station.id, line: [station.lineName])
        /// 需要填充textField
        selectAction?.stationResultTableViewController(viewController: self, textFieldShouldFill: station.name, stationId: station.id, line: [station.lineName])
    }
}
